
package com.jinlejia.erp.ui.common;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.URLUtil;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.jinlejia.erp.R;
import com.jinlejia.erp.databinding.ActivityViewPagerBinding;
import com.weight.CustomToast;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Locale;

import uk.co.senab.photoview.PhotoView;


public class ImageViewPagerActivity extends AppCompatActivity {
    private ArrayList<String> imgs = new ArrayList<>();
    private ArrayList<String> names = new ArrayList<>();
    private int mPosition;
    private ActivityViewPagerBinding binding;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_view_pager);

        if (getIntent().hasExtra("check")){
            binding.title.setVisibility(View.VISIBLE);
            binding.save.setVisibility(View.VISIBLE);
        }
        if (getIntent().hasExtra("position")){
            mPosition = getIntent().getIntExtra("position",1);
        }

        imgs = getIntent().getStringArrayListExtra("imgs");
        names = getIntent().getStringArrayListExtra("names");
        if (names!=null && names.size()!=0 && names.size()>=mPosition-1 && imgs != null){
            String nameTitle = String.format(Locale.CHINESE, "%s %d/%d", names.get(mPosition-1),mPosition, imgs.size());
            binding.title.setText(nameTitle);
        }
        if (names==null && imgs!=null){
            String nameTitle = String.format(Locale.CHINESE, "%d/%d", mPosition,imgs.size());
            binding.title.setText(nameTitle);
        }
        ImageView back = findViewById(R.id.id_back);
        back.setOnClickListener(v -> finish());

        binding.save.setOnClickListener(view -> {
            String url = imgs.get(mPosition-1);
            if (URLUtil.isNetworkUrl(url)){
                new getImageCacheAsyncTask(ImageViewPagerActivity.this)
                        .execute(imgs.get(mPosition-1));
            }

        });

        binding.viewPager.setAdapter(new SamplePagerAdapter());
        binding.viewPager.setCurrentItem(mPosition - 1);

        binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mPosition = position +1;
                if (names!=null && names.size()!=0 && names.size()>=position && imgs!=null){
                    String nameTitle = String.format(Locale.CHINESE, "%s %d/%d", names.get(position),mPosition, imgs.size());
                    binding.title.setText(nameTitle);
                }
                if (names==null && imgs!=null){
                    String nameTitle = String.format(Locale.CHINESE, "%d/%d", mPosition,imgs.size());
                    binding.title.setText(nameTitle);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    class SamplePagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return imgs.size();
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            PhotoView photoView = new PhotoView(container.getContext());
            String url = imgs.get(position);
            if (URLUtil.isNetworkUrl(url)){
                Glide.with(ImageViewPagerActivity.this).load(imgs.get(position)).placeholder(R.mipmap.ic_no_img).into(photoView);
            }else {
                File file = new File(imgs.get(position));
                //Glide 加载本地图片
                Glide.with(ImageViewPagerActivity.this).load(file).into(photoView);
            }
            container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }

    private class getImageCacheAsyncTask extends AsyncTask<String, Void, File> {
        private final Context context;

        public getImageCacheAsyncTask(Context context) {
            this.context = context;
        }

        @Override
        protected File doInBackground(String... params) {
            String imgUrl =  params[0];
            try {
                return Glide.with(context)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get();
            } catch (Exception ex) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {
            if (result == null) {
                return;
            }
            //此path就是对应文件的缓存路径
            String path = result.getPath();
            Bitmap bmp = BitmapFactory.decodeFile(path);
            if (bmp != null ){
                SavePicture(bmp);
                CustomToast.showToast(ImageViewPagerActivity.this,"保存成功",2000);
            }else {
                CustomToast.showToast(ImageViewPagerActivity.this,"保存失败",2000);
            }

        }

        private void SavePicture(Bitmap bitmap) {
            File appDir = new File(Environment.getExternalStorageDirectory(), "HouseTypePicture");//在SD卡中创建一个文件夹
            if (!appDir.exists()) {//如果该文件夹不存在，则创建一个文件夹
                appDir.mkdir();
            }
            try {
                String fileName = System.currentTimeMillis() + ".jpg";
                File file = new File(appDir, fileName);
                FileOutputStream out = null;
                out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG,100, out);
                out.flush();
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                ImageViewPagerActivity.this.sendBroadcast(intent);//这个广播的目的就是更新图库，发了这个广播进入相册就可以找到你保存的图片了！，记得要传你更新的file哦

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
